package com.toocms.jinjuhang.ui.mine.receiver_address

import android.app.Application
import android.os.Bundle
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.MyAddressData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger
import com.toocms.tab.bus.event.SingleLiveEvent

class ReceiverAddressModel(application: Application, val bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {

    val actionObservableField by lazy {
        val content = bundle?.getString(Constants.BundleKey.KEY_ACTION, Constants.Extra.ACTION_VIEW)
        ObservableField(content)
    }

    val items = ObservableArrayList<ReceiverAddressItemModel>()
    val itemBinding = ItemBinding.of<ReceiverAddressItemModel>(
        BR.receiverAddressItemModel, R.layout.item_receiver_address
    )

    val stopRefreshSingleLiveEvent = SingleLiveEvent<Unit>()

    val refreshBindingCommand = BindingCommand<BindingAction>(BindingAction {
        refresh()
    })

    val addNewestAddressClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        startFragment(EditReceiverAddressFgt::class.java)
    })

    init {
        initializeMessenger()
        refresh(true)
    }

    private fun initializeMessenger() {
        Messenger.getDefault().register(this, Constants.MessengerToken.TOKEN_REFRESH_ADDRESS) {
            refresh()
        }
    }

    private fun refresh(isShowLoading: Boolean = false) {
        myAddress(isShowLoading)
    }

    private fun myAddress(isShowLoading: Boolean) {
        requestData(Urls.Center.MY_ADDRESS,
            mapOf(Pair("member_id", UserRepository.user.member_id)),
            resultClass = MyAddressData::class.java,
            isShowLoading = isShowLoading,
            result = {
                items.clear()
                it.list?.forEach {
                    items += ReceiverAddressItemModel(this, ObservableField(it))
                }
            },
            finish = {
                stopRefreshSingleLiveEvent.call()
            })
    }
}